﻿using System;
using System.Data;
using System.Data.Common;
using System.Configuration;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Shuba.Model;

namespace Shuba.Data
{
    public class TransactionLog
    {
        public TransactionLog()
        { }

        public List<TransactionLogInfo> GetList(string AppID, DateTime startDate, DateTime endDate)
        {
            List<TransactionLogInfo> list = new List<TransactionLogInfo>();
            //Database db = DatabaseFactory.CreateDatabase();
            Database db = DBConnection.CreateDatabase();
            string sql;
            DbCommand cmd;

            sql = "SELECT TRANS_DATE, USER_NAME, TRANS_TYPE, TRANS_DESC FROM V_TRANSACTION_LOG WHERE (APP_ID = @APP_ID) AND TRANS_DATE >= @START_DATE AND TRANS_DATE <= DATEADD(day, 1, @END_DATE) ORDER BY TRANS_DATE DESC";
            cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd, "@APP_ID", DbType.String, AppID);
            db.AddInParameter(cmd, "@START_DATE", DbType.DateTime, startDate);
            db.AddInParameter(cmd, "@END_DATE", DbType.DateTime, endDate.AddHours(23.99));

            using (IDataReader dr = db.ExecuteReader(cmd))
            {
                while (dr.Read())
                {
                    list.Add(new TransactionLogInfo(dr.GetDateTime(0), dr.GetString(1), dr.GetString(2), dr.GetString(3)));
                }
                dr.Close();
            }

            return list;
        }

        public void AddLog(TransactionLogInfo log)
        {
            Database db = DBConnection.CreateDatabase();
            
            DbCommand cmd = db.GetStoredProcCommand("ADD_TRANS_LOG"); 

            string AppId = ConfigurationManager.AppSettings["app.code"];
            if (log.Description.Trim().ToLower().Contains("spada")) AppId = ConfigurationManager.AppSettings["app.code.spada"];

            db.AddInParameter(cmd, "@APP_ID", DbType.String, AppId);
            db.AddInParameter(cmd, "@USER_NAME", DbType.String, log.UserName);
            db.AddInParameter(cmd, "@TRANS_TYPE", DbType.String, log.Type);
            db.AddInParameter(cmd, "@TRANS_DESC", DbType.String, log.Description);

            db.ExecuteNonQuery(cmd);
        }

        public Int16 GetTimeOut()
        {
            Int16 result = 15;
            try
            {
                Database db = DBConnection.CreateDatabase();
                DbCommand cmd = db.GetStoredProcCommand("GET_TIME_OUT");
                result = Convert.ToInt16(db.ExecuteScalar(cmd));
                if (result == 0) result = 15;
            }
            catch (Exception) { }
            return result;
        }
    }
}
